<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
    

    
<!-- Tencent Speed -->
<script>var _speedMark = new Date()</script>
<!-- End Tencent Speed -->
<!-- Tencent Analysis -->
<script async src="//tajs.qq.com/stats?sId=false."></script>
<!-- End Tencent Analysis -->


    



    <meta charset="utf-8">
    
    
    <meta name="google-site-verification" content="CUm1VNyzpZuuHWWTWLOVfbkoMiz6Q9ccqUY5rMp9vcI">

    
    
    <title>三种实现分布式锁的方式 | Edward</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="学习,面试,分布式,redis,zookeeper">
    <meta name="description" content="原文链接：https://blog.csdn.net/wuzhiwei549/article/details/80692278 分布式锁的几种使用方式（redis、zookeeper、数据库）https://blog.csdn.net/u010963948/article/details/79006572 一、为什么要使用分布式锁我们在开发应用的时候，如果需要对某一个共享变量进行多线程同步访问的时">
<meta name="keywords" content="学习,面试,分布式,redis,zookeeper">
<meta property="og:type" content="article">
<meta property="og:title" content="三种实现分布式锁的方式">
<meta property="og:url" content="http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/index.html">
<meta property="og:site_name" content="Edward">
<meta property="og:description" content="原文链接：https://blog.csdn.net/wuzhiwei549/article/details/80692278 分布式锁的几种使用方式（redis、zookeeper、数据库）https://blog.csdn.net/u010963948/article/details/79006572 一、为什么要使用分布式锁我们在开发应用的时候，如果需要对某一个共享变量进行多线程同步访问的时">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/20180111171903380.png">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/2018061414253488.png">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY2NjE2ZWY1MTJkYmQz.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY2ODA5NzE1YjRiYWEx.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/20200406155436.png">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTcyODMzMzJmNTRi.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3A5LnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDNlY2Q1N2I4YzYz.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTQ1NGY4N2FlZjdk.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDk1MWQ2MjljNWM1.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTlmZjFmZjMzNGM5.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDRmNjE3MWI4NjQ2.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY4MDJiNDBmYTE5NzFj.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AxLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3MjkzNWRkZTg5ODMw.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3MjBiNjgzNWI4YWZm.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3Njc3YzYxM2NjZjI4.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/aHR0cHM6Ly9pbWFnZXMyMDE3LmNuYmxvZ3MuY29tL2Jsb2cvODgzMzQwLzIwMTcxMi84ODMzNDAtMjAxNzEyMTUxNjI2NTQxNTItMTgxMDg2OTY4NS5wbmc.jpg">
<meta property="og:image" content="http://springcloud.xn--ses554g/img/20180614145850162.png">
<meta property="og:updated_time" content="2020-04-06T08:09:39.875Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="三种实现分布式锁的方式">
<meta name="twitter:description" content="原文链接：https://blog.csdn.net/wuzhiwei549/article/details/80692278 分布式锁的几种使用方式（redis、zookeeper、数据库）https://blog.csdn.net/u010963948/article/details/79006572 一、为什么要使用分布式锁我们在开发应用的时候，如果需要对某一个共享变量进行多线程同步访问的时">
<meta name="twitter:image" content="http://springcloud.xn--ses554g/img/20180111171903380.png">
    
        <link rel="alternate" type="application/atom+xml" title="Edward" href="/atom.xml">
    
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

    <script>
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https'){
                bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
            }
            else{
                bp.src = 'http://push.zhanzhang.baidu.com/push.js';
            }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    </script>

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu">
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand" style="padding-top: 30%;">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/123.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Edward</h5>
          <a href="mailto:zqmssbd@qq.com" title="zqmssbd@qq.com" class="mail">zqmssbd@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/">
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/archives">
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/tags">
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/categories">
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://github.com/zqmssbd" target="_blank">
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/5333276247" target="_blank">
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://gitee.com/Edward-Z" target="_blank">
                <i class="icon icon-lg icon-link"></i>
                码云
              </a>
            </li>
          
      </ul>
        <div id="tp-weather-widget"></div>
        <script>
            (function(a,h,g,f,e,d,c,b){b=function(){d=h.createElement(g);c=h.getElementsByTagName(g)[0];d.src=e;d.charset="utf-8";d.async=1;c.parentNode.insertBefore(d,c)};a["SeniverseWeatherWidgetObject"]=f;a[f]||(a[f]=function(){(a[f].q=a[f].q||[]).push(arguments)});a[f].l=+new Date();if(a.attachEvent){a.attachEvent("onload",b)}else{a.addEventListener("load",b,false)}}(window,document,"script","SeniverseWeatherWidget","//cdn.sencdn.com/widget2/static/js/bundle.js?t="+parseInt((new Date().getTime() / 100000000).toString(),10)));
            window.SeniverseWeatherWidget('show', {
                flavor: "bubble",
                location: "WT3Q0FW9ZJ3Q",
                geolocation: true,
                language: "zh-Hans",
                unit: "c",
                theme: "auto",
                token: "74eabe8a-0b6b-4a56-86ac-c773a4d98218",
                hover: "enabled",
                container: "tp-weather-widget"
            })
        </script>

        <link rel="stylesheet" href="/css/APlayer.css">
        <div id="player" class="aplayer aplayer-withlist aplayer-fixed" data-id="3895885" data-server="netease" data-type="playlist" data-order="random" data-fixed="true" data-listfolded="false" data-theme="#2D8CF0"></div>
        <script src="/js/APlayer.min.js"></script>
        <script src="/js/Meting.min.js"></script>

        


        

    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">三种实现分布式锁的方式</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">三种实现分布式锁的方式</h1>
        <h5 class="title">你真的还不够，不够勤奋和努力。</h5>
        <h5 class="subtitle">
            
                <time datetime="2020-03-30T07:20:55.000Z" itemprop="datePublished" class="page-time">
  2020-03-30
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/">技术文章</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/">redis</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/中间件/">中间件</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/中间件/zookeeper/">zookeeper</a></li></ul></li></ul></li></ul></li></ul>

            
        </h5>
    </div>

    

    <script>
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https'){
                bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
            }
            else{
                bp.src = 'http://push.zhanzhang.baidu.com/push.js';
            }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    </script>
</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#一、为什么要使用分布式锁"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、为什么要使用分布式锁</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#二、分布式锁应该具备哪些条件"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、分布式锁应该具备哪些条件</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#三、分布式锁的三种实现方式"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、分布式锁的三种实现方式</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#一-基于数据库实现排他锁"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">(一)基于数据库实现排他锁</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#方案1"><span class="post-toc-number">3.1.1.</span> <span class="post-toc-text">方案1</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#方案2"><span class="post-toc-number">3.1.2.</span> <span class="post-toc-text">方案2</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#缺点："><span class="post-toc-number">3.1.3.</span> <span class="post-toc-text">缺点：</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#解决方案："><span class="post-toc-number">3.1.4.</span> <span class="post-toc-text">解决方案：</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#二-基于redis实现"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">(二)基于redis实现</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#方案"><span class="post-toc-number">3.2.1.</span> <span class="post-toc-text">方案:</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#缺点：-1"><span class="post-toc-number">3.2.2.</span> <span class="post-toc-text">缺点：</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#三-基于zookeeper实现"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">(三)基于zookeeper实现</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Zookeeper分布式锁的原理"><span class="post-toc-number">3.3.1.</span> <span class="post-toc-text">Zookeeper分布式锁的原理</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#获取锁"><span class="post-toc-number">3.3.1.1.</span> <span class="post-toc-text">获取锁</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#释放锁"><span class="post-toc-number">3.3.1.2.</span> <span class="post-toc-text">释放锁</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#方案："><span class="post-toc-number">3.3.1.3.</span> <span class="post-toc-text">方案：</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#缺点：-2"><span class="post-toc-number">3.3.1.4.</span> <span class="post-toc-text">缺点：</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#总结"><span class="post-toc-number">3.4.</span> <span class="post-toc-text">总结</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#三种方案的比较"><span class="post-toc-number">3.5.</span> <span class="post-toc-text">三种方案的比较</span></a></li></ol></li></ol>
            <!--<div id="toc" class="toc-article">-->
                <!--<strong class="toc-title">文章目录</strong>-->
                <!--<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、为什么要使用分布式锁"><span class="toc-number">1.</span> <span class="toc-text">一、为什么要使用分布式锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、分布式锁应该具备哪些条件"><span class="toc-number">2.</span> <span class="toc-text">二、分布式锁应该具备哪些条件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、分布式锁的三种实现方式"><span class="toc-number">3.</span> <span class="toc-text">三、分布式锁的三种实现方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#一-基于数据库实现排他锁"><span class="toc-number">3.1.</span> <span class="toc-text">(一)基于数据库实现排他锁</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#方案1"><span class="toc-number">3.1.1.</span> <span class="toc-text">方案1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#方案2"><span class="toc-number">3.1.2.</span> <span class="toc-text">方案2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#缺点："><span class="toc-number">3.1.3.</span> <span class="toc-text">缺点：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#解决方案："><span class="toc-number">3.1.4.</span> <span class="toc-text">解决方案：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#二-基于redis实现"><span class="toc-number">3.2.</span> <span class="toc-text">(二)基于redis实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#方案"><span class="toc-number">3.2.1.</span> <span class="toc-text">方案:</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#缺点：-1"><span class="toc-number">3.2.2.</span> <span class="toc-text">缺点：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#三-基于zookeeper实现"><span class="toc-number">3.3.</span> <span class="toc-text">(三)基于zookeeper实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Zookeeper分布式锁的原理"><span class="toc-number">3.3.1.</span> <span class="toc-text">Zookeeper分布式锁的原理</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#获取锁"><span class="toc-number">3.3.1.1.</span> <span class="toc-text">获取锁</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#释放锁"><span class="toc-number">3.3.1.2.</span> <span class="toc-text">释放锁</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#方案："><span class="toc-number">3.3.1.3.</span> <span class="toc-text">方案：</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#缺点：-2"><span class="toc-number">3.3.1.4.</span> <span class="toc-text">缺点：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#总结"><span class="toc-number">3.4.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#三种方案的比较"><span class="toc-number">3.5.</span> <span class="toc-text">三种方案的比较</span></a></li></ol></li></ol>-->
            <!--</div>-->
        </nav>
    </aside>




<article id="post-三种实现分布式锁的方式" class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">三种实现分布式锁的方式</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-03-30 15:20:55" datetime="2020-03-30T07:20:55.000Z" itemprop="datePublished">2020-03-30</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/">技术文章</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/">redis</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/中间件/">中间件</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术文章/redis/中间件/zookeeper/">zookeeper</a></li></ul></li></ul></li></ul></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style="display:none">
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>原文链接：<a href="https://blog.csdn.net/wuzhiwei549/article/details/80692278" target="_blank" rel="noopener">https://blog.csdn.net/wuzhiwei549/article/details/80692278</a></p>
<p>分布式锁的几种使用方式（redis、zookeeper、数据库）<br><a href="https://blog.csdn.net/u010963948/article/details/79006572" target="_blank" rel="noopener">https://blog.csdn.net/u010963948/article/details/79006572</a></p>
<h2 id="一、为什么要使用分布式锁"><a href="#一、为什么要使用分布式锁" class="headerlink" title="一、为什么要使用分布式锁"></a>一、为什么要使用分布式锁</h2><p>我们在开发应用的时候，如果需要对某一个共享变量进行多线程同步访问的时候，可以使用我们学到的Java多线程的18般武艺进行处理，并且可以完美的运行，毫无Bug！</p>
<p>注意这是单机应用，也就是所有的请求都会分配到当前服务器的JVM内部，然后映射为操作系统的线程进行处理！而这个共享变量只是在这个JVM内部的一块内存空间！</p>
<p>后来业务发展，需要做集群，一个应用需要部署到几台机器上然后做负载均衡，大致如下图：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/20180111171903380.png" alt="负载均衡" title="">
                </div>
                <div class="image-caption">负载均衡</div>
            </figure>
<p>上图可以看到，变量A存在JVM1、JVM2、JVM3三个JVM内存中（这个变量A主要体现是在一个类中的一个成员变量，是一个有状态的对象，例如：UserController控制器中的一个整形类型的成员变量），如果不加任何控制的话，变量A同时都会在JVM分配一块内存，三个请求发过来同时对这个变量操作，显然结果是不对的！即使不是同时发过来，三个请求分别操作三个不同JVM内存区域的数据，变量A之间不存在共享，也不具有可见性，处理的结果也是不对的！</p>
<p>如果我们业务中确实存在这个场景的话，我们就需要一种方法解决这个问题！</p>
<p>为了保证一个方法或属性在高并发情况下的同一时间只能被同一个线程执行，在传统单体应用单机部署的情况下，可以使用Java并发处理相关的API(如ReentrantLock或Synchronized)进行互斥控制。在单机环境中，Java中提供了很多并发处理相关的API。但是，随着业务发展的需要，原单体单机部署的系统被演化成分布式集群系统后，由于分布式系统多线程、多进程并且分布在不同机器上，这将使原单机部署情况下的并发控制锁策略失效，单纯的Java API并不能提供分布式锁的能力。为了解决这个问题就需要一种跨JVM的互斥机制来控制共享资源的访问，这就是分布式锁要解决的问题！</p>
<h2 id="二、分布式锁应该具备哪些条件"><a href="#二、分布式锁应该具备哪些条件" class="headerlink" title="二、分布式锁应该具备哪些条件"></a>二、分布式锁应该具备哪些条件</h2><p>在分析分布式锁的三种实现方式之前，先了解一下分布式锁应该具备哪些条件：</p>
<ol>
<li>在分布式系统环境下，一个方法在同一时间只能被一个机器的一个线程执行； </li>
<li>高可用的获取锁与释放锁； </li>
<li>高性能的获取锁与释放锁； </li>
<li>具备可重入特性； </li>
<li>具备锁失效机制，防止死锁； </li>
<li>具备非阻塞锁特性，即没有获取到锁将直接返回获取锁失败。</li>
</ol>
<h2 id="三、分布式锁的三种实现方式"><a href="#三、分布式锁的三种实现方式" class="headerlink" title="三、分布式锁的三种实现方式"></a>三、分布式锁的三种实现方式</h2><p>目前几乎很多大型网站及应用都是分布式部署的，分布式场景中的数据一致性问题一直是一个比较重要的话题。分布式的CAP理论告诉我们“任何一个分布式系统都无法同时满足<strong>一致性（Consistency）</strong>、<strong>可用性（Availability</strong>和<strong>分区容错性（Partition tolerance）</strong>，最多只能同时满足两项。”所以，很多系统在设计之初就要对这三者做出取舍。在互联网领域的绝大多数的场景中，都需要牺牲强一致性来换取系统的高可用性，系统往往只需要保证“最终一致性”，只要这个最终时间是在用户可以接受的范围内即可。</p>
<p>在很多场景中，我们为了保证数据的最终一致性，需要很多的技术方案来支持，比如分布式事务、分布式锁等。有的时候，我们需要保证一个方法在同一时间内只能被同一个线程执行。</p>
<ol>
<li>基于数据库实现分布式锁； </li>
<li>基于缓存（Redis等）实现分布式锁； </li>
<li>基于Zookeeper实现分布式锁；</li>
</ol>
<h3 id="一-基于数据库实现排他锁"><a href="#一-基于数据库实现排他锁" class="headerlink" title="(一)基于数据库实现排他锁"></a>(一)基于数据库实现排他锁</h3><h4 id="方案1"><a href="#方案1" class="headerlink" title="方案1"></a>方案1</h4><p>表结构</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/2018061414253488.png" alt="表结构" title="">
                </div>
                <div class="image-caption">表结构</div>
            </figure>
<p>获取锁</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO method_lock (method_name, desc) VALUES (&apos;methodName&apos;, &apos;methodName&apos;);</span><br></pre></td></tr></table></figure>
<p>对method_name做了唯一性约束，这里如果有多个请求同时提交到数据库的话，数据库会保证只有一个操作可以成功。</p>
<h4 id="方案2"><a href="#方案2" class="headerlink" title="方案2"></a>方案2</h4><p>表结构<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">DROP TABLE IF EXISTS `method_lock`;</span><br><span class="line">CREATE TABLE `method_lock` (</span><br><span class="line">  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT &apos;主键&apos;,</span><br><span class="line">  `method_name` varchar(64) NOT NULL COMMENT &apos;锁定的方法名&apos;,</span><br><span class="line">  `state` tinyint NOT NULL COMMENT &apos;1:未分配；2：已分配&apos;,</span><br><span class="line">  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,</span><br><span class="line">  `version` int NOT NULL COMMENT &apos;版本号&apos;,</span><br><span class="line">  `PRIMARY KEY (`id`),</span><br><span class="line">  UNIQUE KEY `uidx_method_name` (`method_name`) USING BTREE</span><br><span class="line">) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT=&apos;锁定中的方法&apos;;</span><br></pre></td></tr></table></figure></p>
<p>先获取锁的信息<br>     select id, method_name, state,version from method_lock where state=1 and method_name=’methodName’;</p>
<p>占有锁<br>       update t_resoure set state=2, version=2, update_time=now() where method_name=’methodName’ and state=1 and version=2;</p>
<p>如果没有更新影响到一行数据，则说明这个资源已经被别人占位了。</p>
<h4 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h4><ol>
<li>这把锁强依赖数据库的可用性，数据库是一个单点，一旦数据库挂掉，会导致业务系统不可用。</li>
<li>这把锁没有失效时间，一旦解锁操作失败，就会导致锁记录一直在数据库中，其他线程无法再获得到锁。</li>
<li>这把锁只能是非阻塞的，因为数据的insert操作，一旦插入失败就会直接报错。没有获得锁的线程并不会进入排队队列，要想再次获得锁就要再次触发获得锁操作。</li>
<li>这把锁是非重入的，同一个线程在没有释放锁之前无法再次获得该锁。因为数据中数据已经存在了。</li>
</ol>
<h4 id="解决方案："><a href="#解决方案：" class="headerlink" title="解决方案："></a>解决方案：</h4><ol>
<li>数据库是单点？搞两个数据库，数据之前双向同步。一旦挂掉快速切换到备库上。</li>
<li>没有失效时间？只要做一个定时任务，每隔一定时间把数据库中的超时数据清理一遍。</li>
<li>非阻塞的？搞一个while循环，直到insert成功再返回成功。</li>
<li>非重入的？在数据库表中加个字段，记录当前获得锁的机器的主机信息和线程信息，那么下次再获取锁的时候先查询数据库，如果当前机器的主机信息和线程信息在数据库可以查到的话，直接把锁分配给他就可以了。</li>
</ol>
<h3 id="二-基于redis实现"><a href="#二-基于redis实现" class="headerlink" title="(二)基于redis实现"></a>(二)基于redis实现</h3><p><strong>*获取锁</strong>使用命令:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SET resource_name my_random_value NX PX 30000</span><br></pre></td></tr></table></figure>
<p>值得注意的是：<br><strong>random_value</strong> 是客户端生成的唯一的字符串。<br><strong>NX</strong> 代表只在键不存在时，才对键进行设置操作。<br><strong>PX 5000</strong> 设置键的过期时间为5000毫秒。</p>
<h4 id="方案"><a href="#方案" class="headerlink" title="方案:"></a>方案:</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">try&#123;</span><br><span class="line">	lock = redisTemplate.opsForValue().setIfAbsent(lockKey, LOCK);</span><br><span class="line">	logger.info(&quot;cancelCouponCode是否获取到锁：&quot;+lock);</span><br><span class="line">	if (lock) &#123;</span><br><span class="line">		// TODO</span><br><span class="line">		redisTemplate.expire(lockKey,1, TimeUnit.MINUTES); //成功设置过期时间</span><br><span class="line">		return res;</span><br><span class="line">	&#125;else &#123;</span><br><span class="line">		logger.info(&quot;cancelCouponCode没有获取到锁，不执行任务!&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;finally&#123;</span><br><span class="line">	if(lock)&#123;	</span><br><span class="line">		redisTemplate.delete(lockKey);</span><br><span class="line">		logger.info(&quot;cancelCouponCode任务结束，释放锁!&quot;);		</span><br><span class="line">	&#125;else&#123;</span><br><span class="line">		logger.info(&quot;cancelCouponCode没有获取到锁，无需释放锁!&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="缺点：-1"><a href="#缺点：-1" class="headerlink" title="缺点："></a>缺点：</h4><p>在这种场景（主从结构）中存在明显的竞态:<br>    客户端A从master获取到锁，<br>    在master将锁同步到slave之前，master宕掉了。<br>    slave节点被晋级为master节点，<br>    客户端B取得了同一个资源被客户端A已经获取到的另外一个锁。<strong>安全失效</strong>！</p>
<h3 id="三-基于zookeeper实现"><a href="#三-基于zookeeper实现" class="headerlink" title="(三)基于zookeeper实现"></a>(三)基于zookeeper实现</h3><p>让我们来回顾一下Zookeeper节点的概念：<br><img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY2NjE2ZWY1MTJkYmQz.jpg" alt="image"></p>
<p>Zookeeper的数据存储结构就像一棵树，这棵树由节点组成，这种节点叫做Znode。</p>
<p>Znode分为四种类型：</p>
<p>1.<strong>持久节点 （PERSISTENT）</strong></p>
<p>默认的节点类型。创建节点的客户端与zookeeper断开连接后，该节点依旧存在 。</p>
<p>2.<strong>持久节点顺序节点（PERSISTENT_SEQUENTIAL）</strong></p>
<p>所谓顺序节点，就是在创建节点时，Zookeeper根据创建的时间顺序给该节点名称进行编号：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY2ODA5NzE1YjRiYWEx.jpg" alt="持久节点顺序节点" title="">
                </div>
                <div class="image-caption">持久节点顺序节点</div>
            </figure>
<p>3.<strong>临时节点（EPHEMERAL）</strong></p>
<p>和持久节点相反，当创建节点的客户端与zookeeper断开连接后，临时节点会被删除：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/20200406155436.png" alt="临时节点" title="">
                </div>
                <div class="image-caption">临时节点</div>
            </figure>
<p>4.<strong>临时顺序节点（EPHEMERAL_SEQUENTIAL）</strong></p>
<p>顾名思义，临时顺序节点结合和临时节点和顺序节点的特点：在创建节点时，Zookeeper根据创建的时间顺序给该节点名称进行编号；当创建节点的客户端与zookeeper断开连接后，临时节点会被删除。</p>
<h4 id="Zookeeper分布式锁的原理"><a href="#Zookeeper分布式锁的原理" class="headerlink" title="Zookeeper分布式锁的原理"></a>Zookeeper分布式锁的原理</h4><p>Zookeeper分布式锁恰恰应用了临时顺序节点。具体如何实现呢？让我们来看一看详细步骤：</p>
<h5 id="获取锁"><a href="#获取锁" class="headerlink" title="获取锁"></a>获取锁</h5><p>首先，在Zookeeper当中创建一个持久节点ParentLock。当第一个客户端想要获得锁时，需要在ParentLock这个节点下面创建一个<strong>临时顺序节点</strong> Lock1。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTcyODMzMzJmNTRi.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>之后，Client1查找ParentLock下面所有的临时顺序节点并排序，判断自己所创建的节点Lock1是不是顺序最靠前的一个。如果是第一个节点，则成功获得锁。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3A5LnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDNlY2Q1N2I4YzYz.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>这时候，如果再有一个客户端 Client2 前来获取锁，则在ParentLock下载再创建一个临时顺序节点Lock2。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTQ1NGY4N2FlZjdk.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>Client2查找ParentLock下面所有的临时顺序节点并排序，判断自己所创建的节点Lock2是不是顺序最靠前的一个，结果发现节点Lock2并不是最小的。</p>
<p>于是，Client2向排序仅比它靠前的节点Lock1注册<strong>Watcher</strong>，用于监听Lock1节点是否存在。这意味着Client2抢锁失败，进入了等待状态。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDk1MWQ2MjljNWM1.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>
<p>这时候，如果又有一个客户端Client3前来获取锁，则在ParentLock下载再创建一个临时顺序节点Lock3。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NTlmZjFmZjMzNGM5.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>Client3查找ParentLock下面所有的临时顺序节点并排序，判断自己所创建的节点Lock3是不是顺序最靠前的一个，结果同样发现节点Lock3并不是最小的。</p>
<p>于是，Client3向排序仅比它靠前的节点<strong>Lock2</strong>注册Watcher，用于监听Lock2节点是否存在。这意味着Client3同样抢锁失败，进入了等待状态。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3NDRmNjE3MWI4NjQ2.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>这样一来，Client1得到了锁，Client2监听了Lock1，Client3监听了Lock2。这恰恰形成了一个等待队列，很像是Java当中ReentrantLock所依赖的</p>
<h5 id="释放锁"><a href="#释放锁" class="headerlink" title="释放锁"></a>释放锁</h5><p>释放锁分为两种情况：</p>
<p><strong>1.任务完成，客户端显示释放</strong><br>当任务完成时，Client1会显示调用删除节点Lock1的指令。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY4MDJiNDBmYTE5NzFj.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p><strong>2.任务执行过程中，客户端崩溃</strong><br>获得锁的Client1在任务执行过程中，如果Duang的一声崩溃，则会断开与Zookeeper服务端的链接。根据临时节点的特性，相关联的节点Lock1会随之自动删除。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AxLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3MjkzNWRkZTg5ODMw.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>由于Client2一直监听着Lock1的存在状态，当Lock1节点被删除，Client2会立刻收到通知。这时候Client2会再次查询ParentLock下面的所有节点，确认自己创建的节点Lock2是不是目前最小的节点。如果是最小，则Client2顺理成章获得了锁。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3MjBiNjgzNWI4YWZm.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>同理，如果Client2也因为任务完成或者节点崩溃而删除了节点Lock2，那么Client3就会接到通知。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cDovL3AzLnBzdGF0cC5jb20vbGFyZ2UvcGdjLWltYWdlLzE1Mjg1MTExMDY3Njc3YzYxM2NjZjI4.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>最终，Client3成功得到了锁。</p>
<h5 id="方案："><a href="#方案：" class="headerlink" title="方案："></a>方案：</h5><p>可以直接使用zookeeper第三方库<a href="https://curator.apache.org/" target="_blank" rel="noopener">Curator</a>客户端，这个客户端中封装了一个可重入的锁服务。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/aHR0cHM6Ly9pbWFnZXMyMDE3LmNuYmxvZ3MuY29tL2Jsb2cvODgzMzQwLzIwMTcxMi84ODMzNDAtMjAxNzEyMTUxNjI2NTQxNTItMTgxMDg2OTY4NS5wbmc.jpg" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure></p>
<p>Curator提供的InterProcessMutex是分布式锁的实现。acquire方法用户获取锁，release方法用于释放锁。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">https://github.com/apache/curator/</span><br></pre></td></tr></table></figure>
<h5 id="缺点：-2"><a href="#缺点：-2" class="headerlink" title="缺点："></a>缺点：</h5><p>  性能上可能并没有缓存服务那么高。因为每次在创建锁和释放锁的过程中，都要动态创建、销毁瞬时节点来实现锁功能。ZK中创建和删除节点只能通过Leader服务器来执行，然后将数据同不到所有的Follower机器上。</p>
<p>其实，使用Zookeeper也有可能带来并发问题，只是并不常见而已。考虑这样的情况，由于网络抖动，客户端可ZK集群的session连接断了，那么zk以为客户端挂了，就会删除临时节点，这时候其他客户端就可以获取到分布式锁了。就可能产生并发问题。这个问题不常见是因为zk有重试机制，一旦zk集群检测不到客户端的心跳，就会重试，Curator客户端支持多种重试策略。多次重试之后还不行的话才会删除临时节点。（所以，选择一个合适的重试策略也比较重要，要在锁的粒度和并发之间找一个平衡。）</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>下面的表格总结了Zookeeper和Redis分布式锁的优缺点：</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/img/20180614145850162.png" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>
<h3 id="三种方案的比较"><a href="#三种方案的比较" class="headerlink" title="三种方案的比较"></a>三种方案的比较</h3><p>上面几种方式，哪种方式都无法做到完美。就像CAP一样，在复杂性、可靠性、性能等方面无法同时满足，所以，根据不同的应用场景选择最适合自己的才是王道。</p>
<p>从理解的难易程度角度（从低到高）</p>
<p>数据库 &gt; 缓存 &gt; Zookeeper</p>
<p>从实现的复杂性角度（从低到高）</p>
<p>Zookeeper &gt;= 缓存 &gt; 数据库</p>
<p>从性能角度（从高到低）</p>
<p>缓存 &gt; Zookeeper &gt;= 数据库</p>
<p>从可靠性角度（从高到低）</p>
<p>Zookeeper &gt; 缓存 &gt; 数据库</p>
<p>Refrence:<br><a href="https://www.cnblogs.com/austinspark-jessylu/p/8043726.html" target="_blank" rel="noopener">https://www.cnblogs.com/austinspark-jessylu/p/8043726.html</a></p>
<p><a href="https://www.toutiao.com/a6558681932786303501/?tt_from=weixin&amp;utm_campaign=client_share&amp;timestamp=1528800534&amp;app=news_article&amp;utm_source=weixin&amp;iid=34667892860&amp;utm_medium=toutiao_ios&amp;wxshare_count=1" target="_blank" rel="noopener">https://www.toutiao.com/a6558681932786303501/?tt_from=weixin&amp;utm_campaign=client_share&amp;timestamp=1528800534&amp;app=news_article&amp;utm_source=weixin&amp;iid=34667892860&amp;utm_medium=toutiao_ios&amp;wxshare_count=1</a></p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-06T08:09:39.875Z" itemprop="dateUpdated">2020-04-06 16:09:39</time>
</span><br>


        
    </div>
    
    <footer>
        <a href="http://springcloud.xn--ses554g">
            <img src="/img/123.png" alt="Edward">
            Edward
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/zookeeper/">zookeeper</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/分布式/">分布式</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/学习/">学习</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/面试/">面试</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&title=《三种实现分布式锁的方式》 — Edward&pic=http://springcloud.xn--ses554g/img/123.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&title=《三种实现分布式锁的方式》 — Edward&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《三种实现分布式锁的方式》 — Edward&url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&via=http://springcloud.xn--ses554g" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2020/03/30/分布式Session/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">分布式Session</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2020/03/30/Redis常见面试题目/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Redis常见面试题目</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "NHOU6qcrdobSwD5wwUJJ31pQ-gzGzoHsz",
            appKey: "E0RJgPMPwkjfMBOA88EalSzJ",
            avatar: "mm",
            placeholder: "Just go go",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        <p>
    <span id="busuanzi_container_site_uv">
        站点总访客数：30<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv">
        站点总访问量：425<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>Edward &copy; 2017 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&title=《三种实现分布式锁的方式》 — Edward&pic=http://springcloud.xn--ses554g/img/123.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&title=《三种实现分布式锁的方式》 — Edward&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《三种实现分布式锁的方式》 — Edward&url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/&via=http://springcloud.xn--ses554g" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://springcloud.xn--ses554g/2020/03/30/三种实现分布式锁的方式/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":200,"height":400},"mobile":{"show":false}});</script></body>
</html>
